<?php if (!defined("_INDEX")) { header("Location: /"); die; }

/** @var $user User */
if (!$user->isAdmin()) {
	goToPage();
}

set_time_limit(0);

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
	goToPage();
}

$start_time = microtime(true);

// set flag is working
/** @var $db MySQL */
$db->sendQuery("update `settings` set `monitor_flag` = '1' limit 1");

$email = $db->getCell("select `email` from `settings` limit 1");

// INSURERS

/** @var $route Router */
$from = UV::readInt($route->POST('from'));
$to = UV::readInt($route->POST('to'));

$query = "select `company_id`,`address`,`phone`,`donor`,`cookie`
	from `companies`
	where
		(`address` != '' or `phone` != '') and
		`donor` != '' and `cookie` != '-1' and
		`company_id` between '{$from}' and '{$to}'
	order by `company_id`";
$companies = $db->getTable($query);

$cc = 0;
foreach ($companies as $company) {

	// init
	$search = array(
		"'[\s,-\.;\";]*'",
		"'«'",
		"'»'",
	);
	$address = preg_replace($search,"",$company['address']);

	$phones = array();
	foreach (explode(",",$company['phone']) as $key=>$phone){
		if ($phone != ""){
			$phones['source'][$key] = trim($phone);
			$phones['cut'][$key] = trim(preg_replace("/[\s,-\.;]*/","",$phone));
		}
	}

	// download and prepare
	if ($company['cookie'] != "") {
		$opts = array(
			'http'=>array(
				'method'=>"GET",
				'header'=>"Cookie: {$company['cookie']}\r\n"
			)
		);
		$context = stream_context_create($opts);
		$content = file_get_contents(trim($company['donor']),false,$context);
	} else {
		$content = file_get_contents(trim($company['donor']));
	}

	if (strlen($content) != 0) {

		$search = array (
				"'<script[^>]*?>.*?</script>'si",	// Вырезает javaScript
				"'<style[^>]*?>.*?<\/style>'si",	// Вырезает css
				"'<[\/\!]*?[^<>]*?>'si",			// Вырезает HTML-теги
				"'&#?[a-z0-9]+;'i",					// Заменяет HTML-сущности
				"'[\r\n\s?,-\.;\"]*'",				// Вырезает пробельные символы
				"'".chr(194).chr(160)."'",			// Вырезает какую-то херню
				"'«'",
				"'»'",
				);
		$content = preg_replace($search,"",$content);

		if (!preg_match('//u', $content)) {
			$address = iconv("UTF-8","cp1251",$address);
			$content = preg_replace(array("'«'","'»'"),"",$content);
		}

		/*var_dump($address);
		echo $content;
		die;*/

		// searching
		$errors = array();

		if ($address != "") {
			$adr_pos = mb_stripos($content,$address);
			if ($adr_pos === false){
				$errors['address'] = false;
			}
		}

		if (!empty($phone)) {
			foreach ($phones['cut'] as $key => $phone) {
				$phone_pos = strpos($content,$phone);
				if ($phone_pos === false){
					$errors['phones'][] = $phones['source'][$key];
				}
			}
		}

		if (!empty($errors)) {

			$query = "insert into `content_monitor` values (null,'$company[company_id]','insurer','".time()."')";

			$monitor_id = $db->sendQuery($query);

			$query = "insert into `content_errors` values ";
			// address error
			if (isset($errors['address'])) {
				$query .= "(null,'$monitor_id','address','$company[address]')";
			}
			// phones error
			if (isset($errors['phones'])) {
				if (isset($errors['address'])){
					$query .= ",";
				}
				$pe_count = count($errors['phones']);
				foreach ($errors['phones'] as $key => $phone){
					$query .= "(null,'$monitor_id','phone','$phone')";
					$query .= ($key < $pe_count - 1) ? "," : "";
				}
			}

			$db->sendQuery($query);
			$cc++;
		}
	}
	$db->sendQuery("update `settings` set `last_company` = '{$company['company_id']}'");
}

// BROKERS
/*$query = "select `broker_id`,`address`,`phone`,`donor`,`cookie`
	from `brokers`
	where
		(`address` != '' or `phone` != '') and
		`donor` != '' and `cookie` != '-1'
	order by `broker_id`";
$brokers = $db->getTable($query);*/

$bc = 0;
$brokers = array();
foreach ($brokers as $broker) {

	// init
	$search = array(
		"'[\s,-\.;\";]*'",
		"'«'",
		"'»'",
	);
	$address = preg_replace($search,"",$broker['address']);
	$phones = array();
	foreach (explode(",",$broker['phone']) as $key=>$phone){
		if ($phone != ""){
			$phones['source'][$key] = trim($phone);
			$phones['cut'][$key] = trim(preg_replace("/[\s,-\.;]*/","",$phone));
		}
	}

	// download and prepare
	if ($broker['cookie'] != "") {
		$opts = array(
			'http'=>array(
				'method'=>"GET",
				'header'=>"Cookie: {$broker['cookie']}\r\n"
			)
		);
		$context = stream_context_create($opts);
		$content = file_get_contents(trim($broker['donor']),false,$context);
	} else {
		$content = file_get_contents(trim($broker['donor']));
	}

	if (strlen($content) != 0){

		$search = array (
				"'<script[^>]*?>.*?</script>'si",	// Вырезает javaScript
				"'<style[^>]*?>.*?<\/style>'si",	// Вырезает css
				"'<[\/\!]*?[^<>]*?>'si",			// Вырезает HTML-теги
				"'&#?[a-z0-9]+;'i",					// Заменяет HTML-сущности
				"'[\r\n\s?,-\.;\"]*'",				// Вырезает пробельные символы
				"'".chr(194).chr(160)."'",			// Вырезает какую-то херню
				"'«'",
				"'»'",
				);
		$content = preg_replace($search,"",$content);

		if (!preg_match('//u', $content)) {
			$address = iconv("UTF-8","cp1251",$address);
			$content = preg_replace(array("'«'","'»'"),"",$content);
		}

		// searching
		$errors = array();

		if ($address != "") {
			$adr_pos = mb_stripos($content,$address);
			if ($adr_pos === false){
				$errors['address'] = false;
			}
		}

		if (!empty($phone)) {
			foreach ($phones['cut'] as $key => $phone) {
				$phone_pos = strpos($content,$phone);
				if ($phone_pos === false){
					$errors['phones'][] = $phones['source'][$key];
				}
			}
		}

		if (!empty($errors)) {

			$query = "insert into `content_monitor` values (null,'$broker[broker_id]','broker','".time()."')";

			$monitor_id = $db->sendQuery($query);

			$query = "insert into `content_errors` values ";
			// address error
			if (isset($errors['address'])) {
				$query .= "(null,'$monitor_id','address','$broker[address]')";
			}
			// phones error
			if (isset($errors['phones'])) {
				if (isset($errors['address'])){
					$query .= ",";
				}
				$pe_count = count($errors['phones']);
				foreach ($errors['phones'] as $key => $phone){
					$query .= "(null,'$monitor_id','phone','$phone')";
					$query .= ($key < $pe_count - 1) ? "," : "";
				}
			}

			$db->sendQuery($query);
			$bc++;
		}
	}
}

// mail it!
if ($cc != 0 || $bc != 0) {

	$headers = "From: ".DOMAIN."\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=utf-8 \r\n";

	$text = "<html><body><p>На ".date("d.m.Y H:i")." произошли следующие изменения:</p><br>";
	if ($cc != 0) {
		$text .= "<p>У ".wordEnding($cc,"компании","компаний","компаний",true,false)." изменились данные</p>";
	}
	if ($bc != 0) {
		$text .= "<p>У ".wordEnding($bc,"брокера","брокеров","брокеров",true,false)." изменились данные</p>";
	}
	$text .= "<p><a href='".DOMAIN."/admin/monitor'>Просмотреть подробнее</a></p></body></html>";

	mail($email, 'Мониторинг', $text , $headers);
}

$end_time = microtime(true);

$work_time = $end_time - $start_time;
$db->sendQuery("update `settings` set `monitor_time` = '$work_time',`monitor_flag` = '0' limit 1");

echo "success";